package org.huzhp.gateway.filter.balance.rule;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Description: ip hash
 * @Author: huzp
 * @CreateDate: 2020/4/17 16:11
 * @Version: 1.0
 */
public class IpHashLoadBalancerRule extends AbstractLoadBalancerRule {

    private static final Logger logger  = LoggerFactory.getLogger(IpHashLoadBalancerRule.class);

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        System.out.println(iClientConfig);
    }

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                int index = this.ipHash(key.toString(),serverCount);
                server = upList.get(index);

                if (logger.isInfoEnabled()){
                    logger.info("IpHash choose server {}",server);
                }

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }
            return server;
        }
    }

    private int ipHash(String ip,int size){
        return ip.hashCode() % size;
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }
}
